#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/socket.h>
#include <bluetooth/bluetooth.h>
#include <bluetooth/rfcomm.h>
#include <netdb.h>

void error(const char *msg)
{
    // TODO: close existing connections
    perror(msg);
    exit(0);
}

int main(int argc, char **argv)
{
    struct sockaddr_rc loc_addr = { 0 }, rem_addr = { 0 };
    struct sockaddr_in serv_addr;
    struct hostent *server;
    char buf[1024] = { 0 };
    int s, client, bytes_read, sockfd, portno, n;
    socklen_t opt = sizeof(rem_addr);

    // allocate bluetooth socket
    s = socket(AF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM);

    // bind socket to port 1 of the first available 
    // local bluetooth adapter
    loc_addr.rc_family = AF_BLUETOOTH;
    loc_addr.rc_bdaddr = *BDADDR_ANY;
    loc_addr.rc_channel = (uint8_t) 1;
    bind(s, (struct sockaddr *)&loc_addr, sizeof(loc_addr));
      
    // put socket into listening mode
    listen(s, 1);
    printf("Receiving connection...\n");
    client = accept(s, (struct sockaddr *)&rem_addr, &opt);

    // TCP/IP socket -------------------------------
    portno = 42620;
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0) 
        error("ERROR opening socket");
    server = gethostbyname("localhost");
    if (server == NULL) {
        fprintf(stderr,"ERROR, no such host\n");
        exit(0);
    }
    bzero((char *) &serv_addr, sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    bcopy((char *)server->h_addr, 
         (char *)&serv_addr.sin_addr.s_addr,
         server->h_length);
    serv_addr.sin_port = htons(portno);
    if (connect(sockfd,(struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0) 
        error("ERROR connecting");
    // TCP/IP socket -------------------------------

    char c;    
    while (c != 'q') {
      ba2str( &rem_addr.rc_bdaddr, buf );
      fprintf(stderr, "accepted connection from %s\n", buf);
      memset(buf, 0, sizeof(buf));

      // read data from the client
      bytes_read = read(client, buf, sizeof(buf));
      if( bytes_read > 0 ) {
          printf("received [%s]\n", buf);
          // forward message
          n = write(sockfd, buf, strlen(buf));
          if (n < 0) {
              error("ERROR writing to socket");
          }
          c = buf[0];
      } else {
          c = 'q';
      }
    };  

    // close connections
    close(sockfd);
    close(client);
    close(s);
    return 0;
}

